<?php

namespace app\admin\service;

use app\admin\dao\ProfessionalQaReplyDao;
use app\admin\model\UM as UM;
use app\common\model\ProfessionalQaReply;
use ShidianUtil\Exception\DataNotExistException;

/**
 * Class ReplyService
 * @package app\professionalqa\service
 */
class ReplyService
{
    private ProfessionalQaReplyDao $professionalQaReplyDao;

    public function __construct(ProfessionalQaReplyDao $professionalQaReplyDao)
    {
        $this->professionalQaReplyDao = $professionalQaReplyDao;
    }

    /**
     * 列表
     * @param UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return array
     */
    public function index(?UM $user, $qaId, ?int $page = null, ?int $page_size = null): array
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->professionalQaReplyDao->listReplies($qaId, $page, $page_size);
    }

    /**
     * 查询
     * @param \app\admin\model\UM|null $user
     * @param int $id
     * @return \app\common\model\ProfessionalQaReply
     */
    public function read(?UM $user, int $id): ?ProfessionalQaReply
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->professionalQaReplyDao->findByPK($id, true);
    }

    /**
     * 新增
     * @param \app\admin\model\UM $user
     * @param array $params
     * @return  \app\common\model\ProfessionalQaReply
     */
    public function add(UM $user, array $params): ProfessionalQaReply
    {
        return $this->professionalQaReplyDao->insertActive($params, []);
    }

    /**
     * 更新
     * @param \app\admin\model\UM $user
     * @param int $id
     * @param array $params
     * @return \app\common\model\ProfessionalQaReply
     */
    public function modify(UM $user, int $id, array $params): ProfessionalQaReply
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = ProfessionalQaReply::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该对象不存在或已被删除');
        }

        $allowField = [];
        $this->professionalQaReplyDao->updateActive($record, $params, $allowField);

        return $record;
    }

    /**
     * 删除
     * @param UM $user
     * @param int $id
     */
    public function rm(UM $user, int $id): void
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = ProfessionalQaReply::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            return;
        }

        $this->professionalQaReplyDao->deleteModel($record);
    }

}
